package com.zbkj.service.service.saleroom.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.cron.CronException;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.constants.OrderConstants;
import com.zbkj.common.constants.RedisConstants;
import com.zbkj.common.dto.OutOfStockDto;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.*;
import com.zbkj.common.model.order.Order;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.saleroom.RoomProduct;
import com.zbkj.common.model.saleroom.SaleRoom;
import com.zbkj.common.model.user.User;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.*;
import com.zbkj.common.response.*;
import com.zbkj.common.utils.DateUtil;
import com.zbkj.common.utils.GeoUtils;
import com.zbkj.common.utils.PositionUtil;
import com.zbkj.common.utils.RequestUtil;
import com.zbkj.service.dao.*;
import com.zbkj.service.dao.saleroom.RoomProductDao;
import com.zbkj.service.dao.saleroom.SaleRoomDao;
import com.zbkj.service.service.DeliveryPersonnelService;
import com.zbkj.service.service.OrderDetailService;
import com.zbkj.service.service.OrderService;
import com.zbkj.service.service.UserService;
import com.zbkj.service.service.saleroom.ISaleRoomService;
import com.zbkj.service.service.saleroom.RoomProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotNull;
import java.sql.Struct;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 门店信息主Service业务层处理
 *
 * @author zkf
 * @date 2025-02-21
 */
@Service
@Slf4j
public class SaleRoomServiceImpl extends ServiceImpl<SaleRoomDao, SaleRoom> implements ISaleRoomService {

    @Autowired
    private SaleRoomDao saleRoomDao;
    @Autowired
    private UserService userService;
    @Autowired
    private ProductAttrDao productAttrDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ISaleRoomService iSaleRoomService;
    @Autowired
    private RoomProductService roomProductService;
    @Autowired
    private RoomProductDao roomProductDao;
    @Autowired
    private DeliveryPersonnelService deliveryPersonnelService;
//    @Autowired
//    private InOrOutWarehouseSkuDetailsDao inOrOutWarehouseSkuDetailsDao;
//    @Autowired
//    private InOrOutWarehouseOrdersDao inOrOutWarehouseOrdersDao;
//    @Autowired
//    private WarehouseInventoryDao warehouseInventoryDao;


    /**
     * 查询门店信息主
     *
     * @param id 门店信息主主键
     * @return 门店信息主
     */
    @Override
    public SaleRoom selectSaleRoomById(Long id) {
        return saleRoomDao.selectSaleRoomById(id);
    }

    /**
     * 查询门店信息主列表
     *
     * @param saleRoom 门店信息主
     * @return 门店信息主
     */
    @Override
    public PageInfo<SaleRoom> selectSaleRoomList(SaleRoom saleRoom, PageParamRequest pageParamRequest) {
        Page<SaleRoom> saleRoomPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<SaleRoom> list = saleRoomDao.selectSaleRoomList(saleRoom);
        list.forEach(s -> {
            String deliveryRange = s.getDeliveryRange();
            if (StrUtil.isNotBlank(deliveryRange)) {
                List<Double[]> deliveryRangeList = JSONArray.parseArray(deliveryRange, Double[].class);
                s.setDeliveryRangeList(deliveryRangeList);
            }
        });
        return CommonPage.copyPageInfo(saleRoomPage, list);

    }

    /**
     * 新增门店信息主
     *
     * @param saleRoom 门店信息主
     * @return 结果
     */
    @Override
    public int insertSaleRoom(SaleRoom saleRoom) {
        return saleRoomDao.insertSaleRoom(saleRoom);
    }

    /**
     * 修改门店信息主
     *
     * @param saleRoom 门店信息主
     * @return 结果
     */
    @Override
    public int updateSaleRoom(SaleRoom saleRoom) {
        return saleRoomDao.updateSaleRoom(saleRoom);
    }

    /**
     * 批量删除门店信息主
     *
     * @param ids 需要删除的门店信息主主键
     * @return 结果
     */
    @Override
    public int deleteSaleRoomByIds(Long[] ids) {
        return saleRoomDao.deleteSaleRoomByIds(ids);
    }

    /**
     * 删除门店信息主信息
     *
     * @param id 门店信息主主键
     * @return 结果
     */
    @Override
    public int deleteSaleRoomById(Long id) {
        return saleRoomDao.deleteSaleRoomById(id);
    }

    /**
     * 到店自提下单页面到店自提时获取门店接口
     *
     * @param shopSpecIds
     * @return
     */
    @Override
    public List<SaleRoom> selectNearRooms(String position, String shopSpecIds, String city) {
        List<SaleRoom> saleRooms = saleRoomDao.selectNearRooms(shopSpecIds, city);
        Map<Long, List<SaleRoom>> saleRoomList = saleRooms.stream().collect(Collectors.groupingBy(SaleRoom::getId));
        if (CollectionUtils.isEmpty(saleRoomList)) {
            return new ArrayList<>();
        }
        List<SaleRoom> fianlSaleRooms = new ArrayList<>();
        for (Map.Entry<Long, List<SaleRoom>> entry : saleRoomList.entrySet()) {
            List<SaleRoom> rooms = entry.getValue();
            SaleRoom saleRoom = rooms.get(0);

            List<String> dbSpecsIdList = rooms.stream().map(r -> r.getSpecsId()).collect(Collectors.toList());
            List<String> frontSpecsIdList = Arrays.stream(shopSpecIds.split(",")).collect(Collectors.toList());
            List<SaleRoom> inSpecsRooms = rooms.stream().filter(s -> frontSpecsIdList.contains(s.getSpecsId())).collect(Collectors.toList());

            //如果不全部包含
            if (!dbSpecsIdList.containsAll(frontSpecsIdList)) {
                saleRoom.setStock(0);
            } else {
                long count = inSpecsRooms.stream().filter(i -> StringUtils.isEmpty(i.getStock()) || "0".equals(i.getStock())).count();
                if (count > 0) {
                    saleRoom.setStock(0);
                }
            }

            try {
                saleRoom.setDistance(PositionUtil.calculateDistance(position, saleRoom.getRoomPosition()));
            } catch (Exception e) {
                log.info("SaleRoomServiceImpl.selectNearRooms()方法换算经纬度距离异常！");
            }
            fianlSaleRooms.add(saleRoom);
        }
        fianlSaleRooms.sort(Comparator.comparingDouble(p -> Double.parseDouble(p.getDistance()) * 0.3048));
        return fianlSaleRooms;
    }


    /**
     * 同城配送判断门店是否位置超过30KM/门店缺货,返回最近的一个门店
     *
     * @param productAttrRequest
     * @return
     */
    @Override
    public Map<String, Object> getRecentlyRoom(ProductAttrRequest productAttrRequest) {
        List<Integer> shopSpecIdsList = productAttrRequest.getShopSpecIdAndNumberList().stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());
        List<SaleRoom> recentlyRoomlist = saleRoomDao.getRecentlyRooms(shopSpecIdsList, productAttrRequest.getPosition());

        List<SaleRoom> resultList = new ArrayList();
        HashMap<String, Object> hashMap = MapUtil.newHashMap();
        if (CollectionUtil.isEmpty(recentlyRoomlist)) {
            return hashMap;
        }

        Map<Long, List<SaleRoom>> listMap = recentlyRoomlist.stream().collect(Collectors.groupingBy(SaleRoom::getId));
        List<ProductAttrAndNumberRequest> shopSpecIdAndNumberList = productAttrRequest.getShopSpecIdAndNumberList();
        List<Integer> collect1 = shopSpecIdAndNumberList.stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());
        for (Long id : listMap.keySet()) {
            List<SaleRoom> list = listMap.get(id);
            List<Integer> collect = list.stream().map(m -> Integer.valueOf(m.getSpecsId())).collect(Collectors.toList());
            if (collect.containsAll(collect1)) {
                //判断库存是否符合
                list.forEach(saleRoom -> {
                    shopSpecIdAndNumberList.forEach(s -> {
                        if (s.getShopSpecId().toString().equals(saleRoom.getSpecsId()) && s.getNumber() <= saleRoom.getStock() && Double.valueOf(saleRoom.getDistance()) < 30) {
                            saleRoom.setIsStock(1);
                            saleRoom.setSpecsId(null);
                            resultList.add(saleRoom);
                        }
                    });
                    return;
                });
            }
        }

//        List<ProductAttrAndNumberRequest> shopSpecIdAndNumberList = productAttrRequest.getShopSpecIdAndNumberList();
//        recentlyRoomlist.forEach(saleRoom -> {
//            shopSpecIdAndNumberList.forEach(s -> {
//                if (s.getShopSpecId().toString().equals(saleRoom.getSpecsId()) && s.getNumber() <= saleRoom.getStock() && Double.valueOf(saleRoom.getDistance()) < 30) {
//                    resultList.add(saleRoom);
//                }
//            });
//
//        });


        if (CollectionUtil.isEmpty(resultList)) {
            return hashMap;
        }
        List<SaleRoom> collect2 = resultList.stream().map(m -> {
            Double.valueOf(m.getDistance());
            return m;
        }).collect(Collectors.toList());

        List<SaleRoom> collect = collect2.stream().sorted(Comparator.comparing(SaleRoom::getIsStock, Comparator.reverseOrder()).thenComparing(SaleRoom::getDistance)).collect(Collectors.toList());
        SaleRoom saleRoom = collect.stream().findFirst().get();
        hashMap.put("roomId", saleRoom.getId());
        hashMap.put("distance", saleRoom.getDistance());
        return hashMap;
    }


    /**
     * 到店自提下单页面到店自提时获取门店接口
     *
     * @param productAttrRequest
     * @return
     */
    @Override
    public List<SaleRoom> getSaleroomsList(ProductAttrRequest productAttrRequest) {
        List<Integer> shopSpecIdsList = productAttrRequest.getShopSpecIdAndNumberList().stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());
        List<SaleRoom> saleroomsList = saleRoomDao.getSaleroomsList(shopSpecIdsList, productAttrRequest.getPosition(), productAttrRequest.getCity());

        Set<SaleRoom> resultList = new HashSet<>();
        List<SaleRoom> saleRoomList = getRoomAll(productAttrRequest.getPosition());
        //为空，则所有门店都没有货，查询所有门店信息返回
        if (CollectionUtil.isEmpty(saleroomsList)) {
            return saleRoomList;
        }
        Map<Long, List<SaleRoom>> listMap = saleroomsList.stream().collect(Collectors.groupingBy(SaleRoom::getId));
        List<ProductAttrAndNumberRequest> shopSpecIdAndNumberList = productAttrRequest.getShopSpecIdAndNumberList();
        List<Integer> collect1 = shopSpecIdAndNumberList.stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());
        for (Long id : listMap.keySet()) {
            List<SaleRoom> list = listMap.get(id);
            List<Integer> collect = list.stream().map(m -> Integer.valueOf(m.getSpecsId())).collect(Collectors.toList());
            if (collect.containsAll(collect1)) {
                //判断库存是否符合
                list.forEach(saleRoom -> {
                    shopSpecIdAndNumberList.forEach(s -> {
                        if (s.getShopSpecId().toString().equals(saleRoom.getSpecsId()) && s.getNumber() <= saleRoom.getStock()) {
                            saleRoom.setIsStock(1);
                            saleRoom.setSpecsId(null);
                            resultList.add(saleRoom);
                        }
                    });
                    return;
                });
            }
        }

        //判断是不是都是来自用一个门店,不是则无货(因为只能在同一家店提货)
//        boolean flag = saleroomsList.stream().map(m -> m.getId()).distinct().count() == 1;
//        if (!flag) {
//            return saleRoomList;
//        }
//        List<ProductAttrAndNumberRequest> shopSpecIdAndNumberList = productAttrRequest.getShopSpecIdAndNumberList();
//        saleroomsList.forEach(saleRoom -> {
//            shopSpecIdAndNumberList.forEach(s -> {
//                if (s.getShopSpecId().toString().equals(saleRoom.getSpecsId()) && s.getNumber() <= saleRoom.getStock()) {
//                    saleRoom.setIsStock(1);
//                    resultList.add(saleRoom);
//                }
//            });
//        });

        //为空，则所有门店都没有货，查询所有门店信息返回
        if (CollectionUtil.isEmpty(resultList)) {
            return saleRoomList;
        }
        //有货,过滤掉有库存的门店
        List<SaleRoom> newList = saleRoomList.stream().filter(a -> resultList.stream().noneMatch(b -> a.getId().equals(b.getId()))).collect(Collectors.toList());
        resultList.addAll(newList);
        List<SaleRoom> collect2 = resultList.stream().map(m -> {
            Double.valueOf(m.getDistance());
            return m;
        }).collect(Collectors.toList());

        List<SaleRoom> collect = collect2.stream().sorted(Comparator.comparing(SaleRoom::getIsStock, Comparator.reverseOrder()).thenComparing(SaleRoom::getDistance)).collect(Collectors.toList());
        return collect;
    }


    /**
     * 查询门店商品信息列表
     *
     * @param saleRoomProductRequest
     * @return
     */
    @Override
    public PageInfo<ProductAndProductAttrValueResponse> selectSaleRoomProductList(SaleRoomProductRequest saleRoomProductRequest) {
        SaleRoom saleRoom = new SaleRoom();
        if (null != saleRoomProductRequest.getOrderNo()) {
            Order order = orderService.getByOrderNo(saleRoomProductRequest.getOrderNo());
            saleRoom = iSaleRoomService.getById(order.getRoomId());
        } else {
            saleRoom = userService.getSaleRoomInfo();
        }
        Page<Order> page = PageHelper.startPage(saleRoomProductRequest.getPage(), saleRoomProductRequest.getLimit());
        List<ProductAndProductAttrValueResponse> productList = productDao.selectProductIdListByRoomId(saleRoom.getId(), saleRoomProductRequest.getKeyword());
        if (CollectionUtil.isEmpty(productList)) {
            return CommonPage.copyPageInfo(page, productList);
        }
        List<Integer> productIdList = productList.stream().filter(f -> f != null).map(m -> m.getId()).collect(Collectors.toList());
        List<ProductAttrValueResponse> list = productAttrDao.selectProductListByProductIdList(productIdList, saleRoom.getId());
        productList.forEach(p -> {
            if (p != null && null != p.getId()) {
                List<ProductAttrValueResponse> collect = list.stream().filter(f -> f.getProductId().equals(p.getId())).collect(Collectors.toList());
                int sum = collect.stream().mapToInt(ProductAttrValueResponse::getStock).sum();
                p.setList(collect)
                        .setAttrValueId(CollectionUtil.isNotEmpty(collect) ? collect.get(0).getId() : null)
                        .setStock(sum);
            }
        });
        return CommonPage.copyPageInfo(page, productList);
    }


    /**
     * 查询门店订单列表
     *
     * @param saleRoomOrderRequest
     * @return
     */
    @Override
    public Map<String, Object> selectOrderList(SaleRoomOrderRequest saleRoomOrderRequest) {
        SaleRoom saleRoom = userService.getSaleRoomInfo();
        Page<Order> page = PageHelper.startPage(saleRoomOrderRequest.getPage(), saleRoomOrderRequest.getLimit());
        Map resultMap = CollectionUtil.newHashMap();
        List<Order> orderList = saleRoomDao.selectOrderList(saleRoom.getId(), saleRoomOrderRequest.getOrderStatus());
        if (CollectionUtil.isEmpty(orderList)) {
            throw new CronException("暂无订单");
        }

        List<OrderFrontDataResponse> responseList = CollUtil.newArrayList();
        for (Order order : orderList) {
            OrderFrontDataResponse infoResponse = new OrderFrontDataResponse();
            BeanUtils.copyProperties(order, infoResponse);
            // 订单详情对象列表
            List<OrderDetail> orderDetailList = orderDetailService.getByOrderNo(order.getOrderNo());
            List<OrderInfoFrontDataResponse> infoResponseList = CollUtil.newArrayList();
            orderDetailList.forEach(e -> {
                OrderInfoFrontDataResponse orderInfoResponse = new OrderInfoFrontDataResponse();
                BeanUtils.copyProperties(e, orderInfoResponse);
                infoResponseList.add(orderInfoResponse);
            });

            //缺货规格以及缺货数量
            if (StrUtil.isNotBlank(order.getOutOfStockJsonStr())) {
                List<OutOfStockDto> outOfStockDtoSet = JSONArray.parseArray(order.getOutOfStockJsonStr(), OutOfStockDto.class);
                infoResponseList.forEach(orderInfoResponse -> {
                    outOfStockDtoSet.forEach(outOfStockDto -> {
                        if (orderInfoResponse.getAttrValueId().equals(outOfStockDto.getProductAttrValueId())) {
                            orderInfoResponse.setOutOfStockNumber(outOfStockDto.getNumber())
                                    .setIsStock(0);
                        }
                    });
                });
            }

            infoResponse.setOrderInfoList(infoResponseList);

            //如果是门店自提和同城配送的话，需要给门店的联系电话
            if (null != order.getRoomId() && (order.getShippingType().equals(OrderConstants.ORDER_SHIPPING_TYPE_PICK_UP) || order.getShippingType().equals(OrderConstants.ORDER_SHIPPING_TYPE_SAME_CITY))) {
                infoResponse.setRoomPhone(saleRoom != null ? saleRoom.getRoomPhone() : "");
            }
            //门店自提，需要给订单用户的手机号
            if (order.getShippingType().equals(OrderConstants.ORDER_SHIPPING_TYPE_PICK_UP)) {
                User user = userService.getById(order.getUid());
                infoResponse.setConsigneePhone(user != null ? user.getPhone() : "");
            }
            //查询配送员手机号,以便联系配送员
            if (null != order.getDeliveryPersonnelId()) {
                DeliveryPersonnel deliveryPersonnel = deliveryPersonnelService.getById(order.getDeliveryPersonnelId());
                Optional.ofNullable(deliveryPersonnel).map(DeliveryPersonnel::getDeliveryPersonnelPhone).ifPresent(f -> {
                    infoResponse.setDeliveryPersonnelPhone(f);
                });
                Optional.ofNullable(deliveryPersonnel).map(DeliveryPersonnel::getDeliveryPersonnelName).ifPresent(f -> {
                    infoResponse.setDeliveryPersonnelName(f);
                });
            }

            responseList.add(infoResponse);
        }

        //查询全部订单时,要查询待自提3、待配送10、配送中11、已完成6状态下的订单数
        List putList = CollectionUtil.newArrayList();
        Map<Integer, Map<String, Integer>> map = saleRoomDao.selectOrderNumberByStatus(saleRoom.getId(), 3, 10, 11, 6, 12, 0);
        if (map.get(3) != null) putList.add(map.get(3));
        if (map.get(10) != null) putList.add(map.get(10));
        if (map.get(11) != null) putList.add(map.get(11));
        if (map.get(6) != null) putList.add(map.get(6));
        if (map.get(12) != null) putList.add(map.get(12));
        if (map.get(0) != null) putList.add(map.get(0));
        resultMap.put("map", putList);
        resultMap.put("orderFrontDataResponseList", CommonPage.copyPageInfo(page, responseList));
        return resultMap;
    }


    /**
     * 扣减门店商品库存
     *
     * @param attrValueId
     * @param num
     * @param operationType
     */
    @Override
    public Boolean operationStock(Integer attrValueId, Integer num, String operationType, Integer roomId) {
        UpdateWrapper<RoomProduct> updateWrapper = new UpdateWrapper<>();
        if (operationType.equals(Constants.OPERATION_TYPE_ADD)) {
            updateWrapper.setSql(StrUtil.format("product_store = product_store + {}", num));
        }
        if (operationType.equals(Constants.OPERATION_TYPE_DELETE)) {
            updateWrapper.setSql(StrUtil.format("product_store = product_store - {}", num));
        }
        updateWrapper.eq("room_id", roomId);
        updateWrapper.eq("product_specs_id", attrValueId);
        boolean update = roomProductService.update(updateWrapper);
        if (!update) {
            log.error("更新商品attrValue失败，attrValueId = {},roomId={}", attrValueId, roomId);
        }
        return true;
//        return update;
    }


    /**
     * 同城配送-预约配送-查询最近的一个配送中心
     *
     * @param positionRequest
     * @return
     */
    @Override
    public SaleRoom selectRecently(PositionRequest positionRequest) {
        return saleRoomDao.selectRecently(positionRequest);
    }


    /**
     * 根据城市查询配送中心列表
     *
     * @param cityRequest
     * @return
     */
    @Override
    public PageInfo<SaleRoom> listByCity(CityRequest cityRequest) {
        Page<Object> startPage = PageHelper.startPage(cityRequest.getPage(), cityRequest.getLimit());
        LambdaQueryWrapper<SaleRoom> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SaleRoom::getCity, cityRequest.getCity());
        List<SaleRoom> list = list(lqw);
        if (StrUtil.isNotBlank(cityRequest.getPosition())) {
            list.forEach(saleRoom -> {
                try {
                    String format = StrUtil.format("{},{}", saleRoom.getRoomPosition().split(",")[1], saleRoom.getRoomPosition().split(",")[0]);
                    saleRoom.setDistance(PositionUtil.calculateDistance(cityRequest.getPosition(), format));
                } catch (Exception e) {

                }
            });
            List<SaleRoom> collect = list.stream().sorted(Comparator.comparing(SaleRoom::getDistance)).collect(Collectors.toList());
            return CommonPage.copyPageInfo(startPage, collect);
        }
        return CommonPage.copyPageInfo(startPage, list);
    }


    /**
     * 查询所有门店所在的城市列表-去重
     *
     * @param pageParamRequest
     * @return
     */
    @Override
    public PageInfo<String> listCityList(PageParamRequest pageParamRequest) {
        Page<Object> startPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<String> list = saleRoomDao.listCityList();
        return CommonPage.copyPageInfo(startPage, list);
    }


    /**
     * 获取所有门店配送范围列表(经纬度数组对象列表)
     *
     * @return
     */
    @Override
    public List<List<Double[]>> getDeliveryRangeList() {
        LambdaQueryWrapper<SaleRoom> lqw = new LambdaQueryWrapper<>();
        lqw.select(SaleRoom::getDeliveryRange);
        lqw.isNotNull(SaleRoom::getDeliveryRange);
        List<SaleRoom> list = list(lqw);
        List<List<Double[]>> resultList = CollUtil.newArrayList();
        list.forEach(saleRoom -> {
            if (null != saleRoom) {
                String deliveryRange = saleRoom.getDeliveryRange();
                if (StrUtil.isNotBlank(deliveryRange)) {
                    List<Double[]> deliveryRangeList = JSONArray.parseArray(deliveryRange, Double[].class);
                    resultList.add(deliveryRangeList);
                }
            }
        });
        return resultList;
    }


    /**
     * 同城配送判断门店是否位置超过30KM/门店缺货,返回最近的一个门店
     *
     * @param productAttrRequest
     * @return
     */
    @Override
    public Map<String, Object> getRecentlyRoomV2(ProductAttrRequest productAttrRequest) {
        List<Integer> shopSpecIdsList = productAttrRequest.getShopSpecIdAndNumberList().stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());
        //查询所有门店商品规格
        List<SaleRoom> recentlyRoomlist = saleRoomDao.getRecentlyRooms(shopSpecIdsList, productAttrRequest.getPosition());

        List<SaleRoom> resultList = new ArrayList();
        HashMap<String, Object> hashMap = MapUtil.newHashMap();
        if (CollectionUtil.isEmpty(recentlyRoomlist)) {
            return hashMap;
        }

        Map<Long, List<SaleRoom>> listMap = recentlyRoomlist.stream().collect(Collectors.groupingBy(SaleRoom::getId));
        List<ProductAttrAndNumberRequest> shopSpecIdAndNumberList = productAttrRequest.getShopSpecIdAndNumberList();
        List<Integer> collect1 = shopSpecIdAndNumberList.stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());

        //满足的用户购买条件的门店id
        List<Long> roomIdList = recentlyRoomlist.stream().map(m -> m.getId()).distinct().collect(Collectors.toList());
        List<RoomProduct> roomProductList = roomProductService.getProductSpecsIdListByRoomIdList(roomIdList);
        Map<Integer, List<RoomProduct>> roomProductMap = roomProductList.stream().collect(Collectors.groupingBy(RoomProduct::getRoomId));

        //无货的规格id
        List<Integer> specsIdList = new ArrayList<>();
        for (Long id : listMap.keySet()) {
            List<SaleRoom> list = listMap.get(id);
            List<RoomProduct> roomProducts = roomProductMap.get(Math.toIntExact(id));
            List<Integer> collect = roomProducts.stream().map(m -> m.getProductSpecsId()).collect(Collectors.toList());
            if (collect.containsAll(collect1)) {
                //判断库存是否符合
                list.forEach(saleRoom -> {
                    shopSpecIdAndNumberList.forEach(s -> {
                        //先判断在不在配送圈内
                        String deliveryRange = saleRoom.getDeliveryRange();
                        if (StrUtil.isNotBlank(deliveryRange)) {
                            List<Double[]> deliveryRangeList = JSONArray.parseArray(deliveryRange, Double[].class);
                            String position = productAttrRequest.getPosition();
                            Double[] point = new Double[]{Double.valueOf(position.split(",")[1]), Double.valueOf(position.split(",")[0])};
                            boolean isRange = GeoUtils.isInside(deliveryRangeList, point);
                            saleRoom.setIsRange(isRange);
                        }
                        //在配送范围内
                        if (saleRoom.getIsRange()) {
                            if (s.getShopSpecId().toString().equals(saleRoom.getSpecsId())) {
                                //在配送范围内有货
                                if (s.getNumber() <= saleRoom.getStock()) {
                                    saleRoom.setIsStock(1);
                                }
                                //在配送范围内无货
                                else {
                                    saleRoom.setIsStock(0)
                                            .setSpecsId(saleRoom.getSpecsId());
                                    specsIdList.add(s.getShopSpecId());
                                }
                                saleRoom.setSpecsId(null);
                                resultList.add(saleRoom);
                            }
                        }
                    });
                    return;
                });
            }
        }
        if (CollectionUtil.isEmpty(resultList)) {
            return hashMap;
        }
        List<SaleRoom> collect2 = resultList.stream().map(m -> {
            Double.valueOf(m.getDistance());
            return m;
        }).collect(Collectors.toList());
        //判断是否在当前营业时间内得
        collect2.forEach(saleRoom -> {
            Boolean isBusinessHours = DateUtil.check(saleRoom.getRoomJobTime().split("-")[0].trim(), saleRoom.getRoomJobTime().split("-")[1].trim());
            saleRoom.setIsBusinessHours(isBusinessHours);
        });
//        List<SaleRoom> collect3 = collect2.stream().filter(f -> DateUtil.check(f.getRoomJobTime().split("-")[0].trim(), f.getRoomJobTime().split("-")[1].trim())).collect(Collectors.toList());

        List<SaleRoom> collect = collect2.stream().sorted(Comparator.comparing(SaleRoom::getIsStock, Comparator.reverseOrder()).thenComparing(SaleRoom::getDistance)).collect(Collectors.toList());
        SaleRoom saleRoom = collect.stream().findFirst().get();
        hashMap.put("roomId", saleRoom.getId());
        hashMap.put("distance", saleRoom.getDistance());
        hashMap.put("isStock", saleRoom.getIsStock());
        hashMap.put("isBusinessHours", saleRoom.getIsBusinessHours());
        hashMap.put("specsIdList", null);
        return hashMap;
    }


    /**
     * 根据收货地址的经纬度查询所属配送范围的门店。如没有,就是快递发货，在配送范围的话，判断是否有库存，有库存且在营业时间直接同城配送，否则预约配送
     *
     * @param productAttrRequest
     * @return
     */
    @Override
    public Map<String, Object> getRecentlyRoomV3(ProductAttrRequest productAttrRequest) {
        LambdaQueryWrapper<SaleRoom> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SaleRoom::getRoomStatus, 1);
        List<SaleRoom> saleRoomList = list(lqw);
        AtomicReference<SaleRoom> s = new AtomicReference<>(new SaleRoom());
        for (SaleRoom saleRoom : saleRoomList) {
            String deliveryRange = saleRoom.getDeliveryRange();
            if (StrUtil.isNotBlank(deliveryRange)) {
                List<Double[]> deliveryRangeList = JSONArray.parseArray(deliveryRange, Double[].class);
                String position = productAttrRequest.getPosition();
                Double[] point = new Double[]{Double.valueOf(position.split(",")[1]), Double.valueOf(position.split(",")[0])};
                boolean isRange = GeoUtils.isInside(deliveryRangeList, point);
                if (isRange) {
                    s.set(saleRoom);
                    break;
                }
            }
        }

        HashMap<String, Object> hashMap = MapUtil.newHashMap();
        //该地址没有可配送的门店
        if (null == s.get().getId()) {
            //是否在配送范围内(false否 true是)
            hashMap.put("isRange", false);
            return hashMap;
        }
        //有可配送的门店
        else {
            Set<Integer> specsIdList = CollUtil.newHashSet();
            //查询是否有货
            List<Integer> productSpecsIdList = productAttrRequest.getShopSpecIdAndNumberList().stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());
            List<RoomProduct> roomProductList = roomProductService.selectByRoomId(s.get().getId(), productSpecsIdList);

            //判断库存
//            List<RoomProduct> collect = roomProductList.stream().filter(f -> f.getProductStore() > 0).collect(Collectors.toList());
            List<RoomProduct> collect = roomProductList.stream().filter(f -> f.getProductStore() > 0 && f.getIsSure() != 0).collect(Collectors.toList());
            if (CollUtil.isEmpty(collect)) {
                hashMap.put("specsIdList", productSpecsIdList);
            } else {
                //有货的规格id
                List<Integer> sIdList = collect.stream().map(m -> m.getProductSpecsId()).collect(Collectors.toList());
                //取差集 (productSpecsIdList - sIdList)
                List<Integer> reduce = productSpecsIdList.stream().filter(item -> !sIdList.contains(item)).collect(Collectors.toList());
                specsIdList.addAll(reduce);

//                List<Integer> idList = roomProductList.stream().filter(f -> f.getProductStore() == 0).map(m -> m.getProductSpecsId()).collect(Collectors.toList());
                List<Integer> idList = roomProductList.stream().filter(f -> f.getProductStore() == 0 || f.getIsSure() == 0).map(m -> m.getProductSpecsId()).collect(Collectors.toList());
                specsIdList.addAll(idList);
                //判断库存
                productAttrRequest.getShopSpecIdAndNumberList().forEach(shopSpecIdAndNumber -> {
                    collect.forEach(roomProduct -> {
                        if (shopSpecIdAndNumber.getShopSpecId().equals(roomProduct.getProductSpecsId())) {
                            if (shopSpecIdAndNumber.getNumber() > roomProduct.getProductStore()) {
                                specsIdList.add(shopSpecIdAndNumber.getShopSpecId());
                            }
                        }
                    });
                });
                hashMap.put("specsIdList", specsIdList);
            }
            //无货或者缺货
            if (null == roomProductList || productSpecsIdList.size() != roomProductList.size()) {
//                hashMap.put("roomId", s.get().getId());
                hashMap.put("distance", s.get().getDistance());
                hashMap.put("isStock", 0);
            } else {
                if (CollUtil.isEmpty(specsIdList)) {
                    hashMap.put("isStock", 1);
                }
            }
            hashMap.put("roomId", s.get().getId());
            //是否在营业时间
            hashMap.put("isBusinessHours", DateUtil.check(s.get().getRoomJobTime().split("-")[0].trim(), s.get().getRoomJobTime().split("-")[1].trim()));
            //是否在配送范围内(false否 true是)
            hashMap.put("isRange", true);
            //营业时间
            hashMap.put("businessHours", s.get().getRoomJobTime());
        }
        return hashMap;
    }


    /**
     * 退款订单列表
     *
     * @param returnOrderListRequest
     * @return
     */
    @Override
    public PageInfo<RefundOrderResponse> getRefundOrderList(ReturnOrderListRequest returnOrderListRequest) {
        Integer userId = userService.getUserId();
        Page<Object> page = PageHelper.startPage(returnOrderListRequest.getPage(), returnOrderListRequest.getLimit());
        List<RefundOrderResponse> list = saleRoomDao.getRefundOrderList(returnOrderListRequest, userId);
        return CommonPage.copyPageInfo(page, list);
    }


//    /**
//     * 出入库单分页列表
//     *
//     * @param inOrOutWarehouseOrdersRequest
//     * @return
//     */
//    @Override
//    public List<InOrOutWarehouseOrders> getListByStatus(InOrOutWarehouseOrdersRequest inOrOutWarehouseOrdersRequest) {
//        SaleRoom saleRoom = userService.getSaleRoomInfo();
//        PageHelper.startPage(inOrOutWarehouseOrdersRequest.getPage(), inOrOutWarehouseOrdersRequest.getLimit());
//        return saleRoomDao.getListByStatus(inOrOutWarehouseOrdersRequest, saleRoom.getId());
//    }
//
//
//    /**
//     * 出入库单详情
//     *
//     * @param idRequest
//     * @return
//     */
//    @Override
//    public PageInfo<InOrOutWarehouseSkuDetails> info(IdRequest idRequest) {
//        InOrOutWarehouseOrders inOrOutWarehouseOrders = inOrOutWarehouseOrdersDao.selectById(idRequest.getId());
//
//        Page<InOrOutWarehouseSkuDetails> page = PageHelper.startPage(idRequest.getPage(), idRequest.getLimit());
//        LambdaQueryWrapper<InOrOutWarehouseSkuDetails> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(InOrOutWarehouseSkuDetails::getTransferOrderNumber, inOrOutWarehouseOrders.getTransferOrderNumber());
//        List<InOrOutWarehouseSkuDetails> list = inOrOutWarehouseSkuDetailsDao.selectList(lqw);
//        list.forEach(inOrOutWarehouseSkuDetails -> {
//            inOrOutWarehouseSkuDetails.setTransferOutStoreThenStock(inOrOutWarehouseSkuDetails.getTransferOutStoreThenStock() == null ? 0 : inOrOutWarehouseSkuDetails.getTransferOutStoreThenStock());
//            inOrOutWarehouseSkuDetails.setTransferInStoreThenStock(inOrOutWarehouseSkuDetails.getTransferInStoreThenStock() == null ? 0 : inOrOutWarehouseSkuDetails.getTransferInStoreThenStock());
//        });
//        return CommonPage.copyPageInfo(page, list);
//    }
//
//
//    /**
//     * 出入库单详情操作(取消-提交)
//     *
//     * @param operateRequest
//     * @return
//     */
//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public Boolean operate(OperateRequest operateRequest) {
//        Integer id = operateRequest.getId();
//        Integer operateType = operateRequest.getOperateType();
//        //调拨出入库单表
//        InOrOutWarehouseOrders inOrOutWarehouseOrders = inOrOutWarehouseOrdersDao.selectById(id);
//        if (null == inOrOutWarehouseOrders) {
//            throw new CrmebException("id不存在");
//        }
//        //2:提交(出库)  3:取消
//        if (operateType == 2) {
//            //1:出库 2:入库
//            if (1 == inOrOutWarehouseOrders.getInOrOutWarehouseType()) {
//                //减去库存
//                LambdaQueryWrapper<InOrOutWarehouseSkuDetails> lqw = Wrappers.lambdaQuery();
//                lqw.eq(InOrOutWarehouseSkuDetails::getTransferOrderNumber, inOrOutWarehouseOrders.getTransferOrderNumber());
//                List<InOrOutWarehouseSkuDetails> list = inOrOutWarehouseSkuDetailsDao.selectList(lqw);
//                list.forEach(inOrOutWarehouseSkuDetails -> {
//                    roomProductDao.updateProductStoreByProductSpecsId(inOrOutWarehouseOrders.getTransferOutRoomWarehouseId(), inOrOutWarehouseSkuDetails.getProductAttrValueId(), inOrOutWarehouseSkuDetails.getNumber());
//                });
//            } else {
//                //入库
//                //先查询该调拨单是否出库了
//                InOrOutWarehouseOrders i = inOrOutWarehouseOrdersDao.selectByTransferOrderNumber(inOrOutWarehouseOrders.getTransferOrderNumber(), 1);
//                if (i != null && i.getInOrOutWarehouseStatus() != 1) {
//                    throw new CrmebException("当前调拨单还未出库,暂不能入库操作");
//                }
//
//                LambdaQueryWrapper<InOrOutWarehouseSkuDetails> lqw = Wrappers.lambdaQuery();
//                lqw.eq(InOrOutWarehouseSkuDetails::getTransferOrderNumber, inOrOutWarehouseOrders.getTransferOrderNumber());
//                List<InOrOutWarehouseSkuDetails> list = inOrOutWarehouseSkuDetailsDao.selectList(lqw);
//                List<RoomProduct> addList = new ArrayList<>();
//                Date from = Date.from(Instant.now());
//
//                list.forEach(t -> {
//                    LambdaQueryWrapper<RoomProduct> l = Wrappers.lambdaQuery();
//                    l.eq(RoomProduct::getRoomId, inOrOutWarehouseOrders.getTransferInRoomWarehouseId());
//                    l.eq(RoomProduct::getProductSpecsId, t.getProductAttrValueId());
//                    RoomProduct roomProduct = roomProductDao.selectOne(l);
//                    if (null != roomProduct) {
//                        roomProduct.setProductStore(roomProduct.getProductStore() + t.getNumber());
//                        roomProductDao.updateById(roomProduct);
//                    } else {
//                        RoomProduct r = new RoomProduct()
////                                .setTransferInfoId(transferOrder.getId())
//                                .setRoomId(inOrOutWarehouseOrders.getTransferInRoomWarehouseId())
//                                .setProductSpecsId(t.getProductAttrValueId())
//                                .setProductStore(t.getNumber())
//                                .setIsSure(1)
//                                .setCreateTime(from);
//                        addList.add(r);
//                    }
//                });
//                if (CollUtil.isNotEmpty(addList)) {
//                    roomProductService.saveBatch(addList);
//                }
//            }
//            //出库、入库都要更新状态
//            inOrOutWarehouseOrders.setInOrOutWarehouseStatus(1);
//            return inOrOutWarehouseOrdersDao.updateById(inOrOutWarehouseOrders) > 0 ? true : false;
//        }
//        //取消
//        else {
//            //1:出库取消 2:入库取消
//            if (1 == inOrOutWarehouseOrders.getInOrOutWarehouseType()) {
//                //出库取消,应也要把入库单取消
//                InOrOutWarehouseOrders i = inOrOutWarehouseOrdersDao.selectByTransferOrderNumber(inOrOutWarehouseOrders.getTransferOrderNumber(), 2);
//                if (i != null) {
//                    i.setInOrOutWarehouseStatus(3);
//                    inOrOutWarehouseOrdersDao.updateById(i);
//                }
//            } else {
//                //入库取消
//                //先查询该调拨单是否出库了
//                InOrOutWarehouseOrders i = inOrOutWarehouseOrdersDao.selectByTransferOrderNumber(inOrOutWarehouseOrders.getTransferOrderNumber(), 1);
//                if (i != null && i.getInOrOutWarehouseStatus() != 1) {
//                    throw new CrmebException("当前调拨单还未出库,暂不能入库取消操作");
//                }
//            }
//            //库存加回去
//            //出库是仓库时
//            if (1 == inOrOutWarehouseOrders.getTransferOutType()) {
//                LambdaQueryWrapper<InOrOutWarehouseSkuDetails> lqw = Wrappers.lambdaQuery();
//                lqw.eq(InOrOutWarehouseSkuDetails::getTransferOrderNumber, inOrOutWarehouseOrders.getTransferOrderNumber());
//                List<InOrOutWarehouseSkuDetails> list = inOrOutWarehouseSkuDetailsDao.selectList(lqw);
//                list.forEach(sku -> {
//                    warehouseInventoryDao.updateAddByProductAttrValueId(inOrOutWarehouseOrders.getTransferInRoomWarehouseId(), sku.getProductAttrValueId(), sku.getNumber());
//                });
//            }
//            //出库是门店时
//            else if (2 == inOrOutWarehouseOrders.getTransferOutType()) {
//                LambdaQueryWrapper<InOrOutWarehouseSkuDetails> lqw = Wrappers.lambdaQuery();
//                lqw.eq(InOrOutWarehouseSkuDetails::getTransferOrderNumber, inOrOutWarehouseOrders.getTransferOrderNumber());
//                List<InOrOutWarehouseSkuDetails> list = inOrOutWarehouseSkuDetailsDao.selectList(lqw);
//                list.forEach(sku -> {
//                    roomProductDao.updateAddProductStoreByProductSpecsId(inOrOutWarehouseOrders.getTransferOutRoomWarehouseId(), sku.getProductAttrValueId(), sku.getNumber());
//                });
//            }
//            //出库取消、入库取消都要改状态
//            inOrOutWarehouseOrders.setInOrOutWarehouseStatus(3);
//            return inOrOutWarehouseOrdersDao.updateById(inOrOutWarehouseOrders) > 0 ? true : false;
//        }
//    }


    private List<SaleRoom> getRoomAll(String position) {
        List<SaleRoom> saleRoomList = list();
        saleRoomList.forEach(saleRoom -> {
            saleRoom.setIsStock(0);
            try {
                saleRoom.setDistance(PositionUtil.calculateDistance(position, saleRoom.getRoomPosition()));
            } catch (Exception e) {

            }
        });
        return saleRoomList;
    }


}